package com.ly.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ly.base.ResponseData;
import com.ly.dto.CarInfoDto;
import com.ly.dto.CarOrderDto;
import com.ly.entity.Car;
import com.ly.entity.CarOrder;
import com.ly.entity.SysUser;
import com.ly.mapper.CarMapper;
import com.ly.mapper.CarOrderMapper;
import com.ly.param.CarAuditParam;
import com.ly.param.CarOrderAddParam;
import com.ly.param.CarOrderParam;
import com.ly.param.CarParam;
import com.ly.service.CarOrderService;
import com.ly.service.CarService;
import com.ly.service.SysUserService;
import com.ly.utils.DateUtils;
import com.ly.utils.OrderCoderUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.Principal;
import java.util.Date;
import java.util.List;


@Service
public class CarOrderServiceImpl extends ServiceImpl<CarOrderMapper, CarOrder> implements CarOrderService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private CarService carService;

    @Autowired
    private CarMapper carMapper;


    @Transactional
    @Override
    public ResponseData addCarOrder(CarOrderAddParam carOrderAddParam, Principal principal) {

        CarOrder carOrder = new CarOrder();

        SysUser sysUser = sysUserService.getByUserName(principal.getName());


        Car car = carService.findByCarId(carOrderAddParam.getCarId());

        if(sysUser.getId().equalsIgnoreCase(car.getCreatedBy())){
            return ResponseData.fail("您不能租借自己发布的车辆！");
        }

        if(car.getLoanableStatus()==1||car.getLoanableStatus()==2){
            return ResponseData.fail("车辆已出租");
        }

        car.setLoanableStatus(1);

        carMapper.updateById(car);


        BeanUtils.copyProperties(carOrderAddParam,carOrder);

        carOrder.setCreatedBy(sysUser.getId());
        carOrder.setCreatedAt(DateUtils.getYyyyMMddHHmmss(new Date()));
        carOrder.setReturnTime(DateUtils.getReturnTime(carOrderAddParam.getLoanableTime())); //预计归还时间
        carOrder.setOrderStatus(0);
//        carOrder.setOrderCode(OrderCoderUtils.getOrderCode(sysUser.getId())); //生成订单编号
        carOrder.setOrderCode(sysUser.getId()+DateUtils.getYyyyMMddHHmmss()); //生成订单编号
//        carOrder.setPrice(carOrderAddParam.getPrice());



        if(sysUser.getBalance()==null||sysUser.getBalance()-carOrder.getPrice()<0){
            return ResponseData.fail("余额不足，请充值后再租借");
        }

        sysUser.setBalance(sysUser.getBalance()-carOrderAddParam.getPrice());

        sysUserService.updateById(sysUser);


        save(carOrder);
        return ResponseData.success("订单生成成功！");
    }

    @Override
    public ResponseData updateCarOrder(CarOrder carOrder, Principal principal) {

        SysUser sysUser = sysUserService.getByUserName(principal.getName());

        CarOrder carOrder1 = getById(carOrder.getId());
        if(carOrder==null){
            return ResponseData.fail("订单不存在!");
        }

        carOrder1.setOrderStatus(carOrder.getOrderStatus());
        carOrder1.setRemark(carOrder.getRemark());

        carOrder1.setUpdatedAt(DateUtils.getYyyyMMddHHmmss(new Date()));
        carOrder1.setUpdatedBy(sysUser.getId());
        saveOrUpdate(carOrder1);

        return ResponseData.success("修改成功");
    }

    @Override
    public Page<CarOrderDto> pageCarOrderList(CarOrderParam carOrderParam) {
        Page<CarOrderDto> page = new Page<>(carOrderParam.getPage(),carOrderParam.getSize());
        return baseMapper.pageCarOrderList(page,carOrderParam.getOrderCode(),carOrderParam.getStatTime(),carOrderParam.getEndTime(),carOrderParam.getKeyValues(),carOrderParam.getOrderStatus(),carOrderParam.getUserId());
    }

    @Override
    public ResponseData deleteCarOrder(String id) {
        CarOrder carOrder = getById(id);
        if(carOrder!=null&&(carOrder.getOrderStatus()==0||carOrder.getOrderStatus()==2)){
            ResponseData.fail("订单还未完成");
        }
        removeById(id);
        return ResponseData.success("删除成功！");
    }

    @Override
    public CarOrder findByCarOrderId(String id) {

        return getById(id);

    }

    @Override
    public List<CarOrder> findByOverdue() {

        return baseMapper.listCarOrder();
    }

    @Override
    public void updateCarOrderList(List<CarOrder> carOrders) {
        updateBatchById(carOrders);
    }

    @Override
    public ResponseData returnCar(String orderId, Principal principal) {

        CarOrder carOrder = getById(orderId);
        if(carOrder==null){
            return ResponseData.fail("订单不存在");
        }

        SysUser sysUser = sysUserService.getByUserName(principal.getName());

        if(!carOrder.getCreatedBy().equalsIgnoreCase(sysUser.getId())){
            return ResponseData.fail("此订单不是您的，您无权归还");
        }

        Car car = carService.findByCarId(carOrder.getCarId());

        //计算归还时间是否在当日，在当日按全款，不足一日按一日计算。
        try {
            int day = -DateUtils.getDays(carOrder.getReturnTime()); //计算时间差
            if(day<=-1){ //逾期处理
                carOrder.setPracticalPrice(carOrder.getPrice()+carOrder.getPenalSum()); //实际支付=金额+逾期金额
                //逾期部分再去用户钱包扣除
                if(sysUser.getBalance()-carOrder.getPenalSum()>=0){
                    sysUser.setBalance(sysUser.getBalance()-carOrder.getPenalSum());
                }else{
                    return ResponseData.fail("余额不足，请联系管理员充值");
                }
                car.setLoanableStatus(0);
            }else{ //不逾期处理

                //计算实际支付金额，提前还车需将金额返还给用户
                Double avg = carOrder.getPrice()/carOrder.getLoanableTime();
                Double p = avg*day;
                if(day==0){
                    carOrder.setPracticalPrice(carOrder.getPrice());
                }else{
                    Double s = carOrder.getPrice()-p; //支付的钱减实际支付的钱
                    carOrder.setPracticalPrice(p);

                    //将提前还车剩余部分返回给用户
                    sysUser.setBalance(sysUser.getBalance()+s);

                }
                //天数未满释放租车位
                car.setLoanableStatus(0);
            }

            carMapper.updateById(car);

            carOrder.setOrderStatus(1); //支付后将订单改为完成
            carOrder.setPracticalTime(DateUtils.getYyyyMMddHHmmss(new Date())); //实际归还时间

            sysUserService.updateById(sysUser);

            updateById(carOrder);

        } catch (Exception e) {
            e.printStackTrace();
        }


        return ResponseData.success("订单支付成功!");
    }


}
